<template>
<el-dialog :visible.sync="visible" :title="title" v-if="visible">
  <el-form :model="formData" label-position="right" label-width="80px" :rules="rules" ref="formData">
    <el-form-item label="图书名称" prop="bookName">
      <el-input placeholder="请输入图书名"  v-model="formData.bookName"/>
    </el-form-item>
    <template v-if="loginInfo.role === 1">
    <el-form-item label="选择作者">
      <el-select @change="changeSelect" @clear="clearSelect" v-model="formData.authorId" clearable filterable>
        <el-option v-for="author in authorList" :key="author.userId" :label="author.name" :value="author.userId" :disabled="author.status === 2"/>
      </el-select>
    </el-form-item>
    <el-form-item label="作者名" prop="authorName">
      <el-input placeholder="作者名" @input="changeAuthorName" v-model="formData.authorName"/>
    </el-form-item>
    </template>
    <el-form-item label="选择分类">
      <el-select v-model="formData.categoryIds" clearable filterable multiple>
        <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId" :disabled="item.status === 2"/>
      </el-select>
    </el-form-item>
    <el-form-item label="图书简介">
      <el-input type="textarea" :rows="3" maxlength="200" show-word-limit placeholder="请输入排序值" :min="0" v-model="formData.profile"/>
    </el-form-item>
    <el-form-item label="图书封面" prop="cover">
      <el-upload :action="uploadUrl" :headers="uploadHeader" :file-list="coverList" list-type="picture-card" :limit="1" ref="coverUpload" :on-success="coverUploadSuccess" :on-exceed="onExceed" :before-upload="beforeUpload">
        <i class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img :src="file.url" alt="" class="el-upload-list__item-thumbnail"/>
          <div class="el-upload-list__item-actions">
            <span @click="showImageDialog(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span @click="removeImage(file,'coverUpload')">
              <i class="el-icon-delete"></i>
            </span>
          </div>
        </div>
      </el-upload>
    </el-form-item>
    <el-form-item label="图书插画">
      <el-upload :action="uploadUrl" :headers="uploadHeader" :file-list="imageList" list-type="picture-card" :limit="5" ref="imageUpload" :on-success="imageUploadSuccess" :on-exceed="onExceed" :before-upload="beforeUpload">
        <i class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img :src="file.url" alt="" class="el-upload-list__item-thumbnail"/>
          <div class="el-upload-list__item-actions">
            <span @click="showImageDialog(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span @click="removeImage(file,'imageUpload')">
              <i class="el-icon-delete"></i>
            </span>
          </div>
        </div>
      </el-upload>
    </el-form-item>
    <el-form-item label="图书状态">
      <el-radio-group v-model="formData.bookStatus">
        <el-radio :label="1">连载中</el-radio>
        <el-radio :label="2">已完结</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="状态">
      <el-radio-group v-model="formData.status">
        <el-radio :label="1">可用</el-radio>
        <el-radio :label="2">禁用</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="update">提交</el-button>
      <el-button type="warning" @click="visible = false">取消</el-button>
    </el-form-item>
  </el-form>
  <el-dialog append-to-body title="查看图片" :visible.sync="showImage" v-if="showImage">
    <div style="height: 100%;width: 100%;display: flex;align-items: center;justify-content: center;">
      <img :src="showImageSrc" alt="" style="display: block;max-height: 100%;max-width: 100%">
    </div>
  </el-dialog>
</el-dialog>
</template>

<script>
const formData = {
  bookId: '',
  bookName: '',
  authorId: '',
  authorName: '',
  profile: '',
  bookStatus: 1,
  cover: '',
  images: [],
  categoryIds: [],
  status: 1
}
export default {
  name: 'BookUpdate',
  data () {
    return {
      visible: false,
      title: '添加数据',
      formData: {
        ...formData
      },
      rules: {
        bookName: [{
          required: true,
          message: '请输入图书名',
          trigger: 'blur'
        }],
        authorName: [{
          required: true,
          message: '请输入作者名',
          trigger: 'blur'
        }],
        categoryIds: [{
          required: true,
          message: '请选择分类',
          trigger: 'blur'
        }],
        cover: [{
          required: true,
          message: '请上传图书封面'
        }]
      },
      uploadUrl: process.env.VUE_APP_BASE_URL + 'upload',
      uploadHeader: {
        token: ''
      },
      coverList: [],
      imageList: [],
      showImage: false,
      showImageSrc: '',
      categoryList: [],
      authorList: [],
      loginInfo: {}
    }
  },
  methods: {
    init (bookId) {
      this.visible = true
      this.formData = { ...formData }
      this.imageList = []
      this.coverList = []
      /* 获取分类列表 */
      this.$http.get('category/select').then(({ data }) => {
        this.categoryList = [...data]
        /* 获取作者列表 */
        this.$http.get('vip/author/select').then(({ data }) => {
          this.authorList = [...data]
          if (bookId) {
            this.title = '修改数据'
            this.$http.get(`book/info/${bookId}`).then(({ data }) => {
              this.formData = { ...data }
              this.coverList = [{ url: `${process.env.VUE_APP_BASE_URL}img/${data.cover}` }]
              /* map函数表示格式化数组 */
              this.imageList = data.imageList.map(item => {
                return {
                  url: `${process.env.VUE_APP_BASE_URL}img/${item.src}`,
                  name: item.src
                }
              })
              this.formData.images = data.imageList.map(item => item.src)
              this.formData.categoryIds = data.categoryList.map(item => item.categoryId)
            })
          }
        })
      })
    },
    update () {
      this.$refs.formData.validate(valid => {
        if (valid) {
          if (this.loginInfo.role === 2) {
            this.formData.authorId = this.loginInfo.userId
            this.formData.authorName = this.loginInfo.nickname
          }
          this.$http.post('book/update', this.formData).then(() => {
            this.$alert(`${this.formData.bookId ? '修改' : '添加'}成功`, { type: 'success' }).then(() => {
              this.visible = false
              this.$emit('onCloseDialog')
            })
          })
        }
      })
    },
    coverUploadSuccess (res) {
      if (res.code === 200) {
        this.formData.cover = res.data
      } else {
        this.$message.error(res.msg)
      }
    },
    imageUploadSuccess (res) {
      if (res.code === 200) {
        this.formData.images.push(res.data)
      } else {
        this.$message.error(res.msg)
      }
    },
    onExceed () {
      this.$message.error('请先删除原图片')
    },
    beforeUpload (file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isImage) {
        this.$message.error('请选择正确的格式！')
      }
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('文件大小不能超过20M！')
      }

      return isImage && isLt20M
    },
    showImageDialog (file) {
      this.showImage = true
      this.showImageSrc = file.url
    },
    removeImage (file, ref) {
      this.$refs[ref].handleRemove(file)
      if (ref === 'coverUpload') {
        this.formData.cover = ''
      } else {
        /* 获取上传成功后的图片名称 */
        const fileName = file.name || file.response.data
        /* 初始化下标 */
        let index = -1
        /* 遍历存放图片名称的数组 */
        for (let i = 0; i < this.formData.images.length; i++) {
          if (this.formData.images[i] === fileName) {
            index = i
            break
          }
        }
        this.formData.images.splice(index, 1)
      }
    },
    changeSelect (val) {
      for (let i = 0; i < this.authorList.length; i++) {
        if (val === this.authorList[i].userId) {
          this.formData.authorName = this.authorList[i].name
          break
        }
      }
    },
    clearSelect () {
      this.formData.authorName = ''
    },
    changeAuthorName (val) {
      let authorId = ''
      for (let i = 0; i < this.authorList.length; i++) {
        if (val === this.authorList[i].name) {
          authorId = this.authorList[i].userId
          break
        }
      }
      this.formData.authorId = authorId
    }
  },
  created () {
    this.$nextTick(() => {
      this.uploadHeader.token = this.$cookies.get('token')
      this.$http.get('userinfo/info').then(({ data }) => {
        this.loginInfo = { ...data }
      })
    })
  }
}
</script>

<style scoped>

</style>
